#!/bin/sh

serial=$(serial)
platform=$(cat /etc/platform)
gpon_xml="/etc/xml_params/gpon_xml_cfg_file.xml"
if [ "$platform" = "GFLT300" ]; then
  # GFLT300 uses a different gpon xml config file.
  gpon_xml="/etc/xml_params/gpon3_xml_cfg_file.xml"
fi

mkdir -p /tmp/xml_params
if [ ! -z "$serial" ]; then
  # Replace the placeholder serial number with the real serial number.
  cat "$gpon_xml" | \
    sed -e "s/AABBCCDDEEFF/$serial/" >/tmp/xml_params/pon_xml_cfg_file.xml
else
  # SERIALXXYYZZ isn't going to be able to join the GPON network.
  # So turn the LED red for hardware failure.
  echo "serial number is blank; will be unable to join GPON network"
  touch /tmp/gpio/ledcontrol/hardware_failure
  # We still need to copy the XML file as well since the first time the board
  # boots in the factory it will have no hnvram variables, including no serial
  # number.
  cp -f "$gpon_xml" /tmp/xml_params/pon_xml_cfg_file.xml
fi
cp -f /etc/xml_params/pon_type_xml_cfg_file_gpon.xml \
  /tmp/xml_params/pon_type_xml_cfg_file.xml
cp -f /etc/xml_params/tpm_xml_cfg_file_gpon.xml \
  /tmp/xml_params/tpm_xml_cfg_file.xml

version="$(cat /etc/version)"
# Strip off the leading gfltxxx- (leaves the part after the dash)
# and limit the length of version to 14 characters.
version="${version#*-}"
version="$(echo "$version" | cut -c 1-14)"
if [ -z "$version" ]; then
  version="TR69CONTROL"
fi
tmpl="/etc/xml_params/omci_xml_cfg_file.tmpl.xml"
cfg="/tmp/xml_params/omci_xml_cfg_file.xml"
sed -e "s/TR69CONTROL/$version/" -e "s/PLATFORM/$platform/" $tmpl > $cfg

case "$1" in
  start)
    echo "Starting data configuration."
    # Clean BM's cause register
    devmem2 0xf10d0050 w 0

    # Set PNC_AGING_LO_THRESH_REGISTERS to maximum value
    devmem2 0xf10c802c w 0x3FFFFFF
    devmem2 0xf10c8030 w 0x3FFFFFF
    devmem2 0xf10c8034 w 0x3FFFFFF
    devmem2 0xf10c8038 w 0x3FFFFFF

    # Double PnC buffers for ports PMAC/GMAC0
    devmem2 0xf10c8000 w 0x377777

    cd /sys/devices/platform/neta/gbe &&
    echo 0 0x2F00 >mh_2B &&
    echo 1 0x1F00 >mh_2B
    ;;
  stop)
    ;;
  restart|reload)
    $0 stop
    $0 start
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
esac
